package com.example.usbhidtool.tcp

import android.annotation.TargetApi
import android.app.*
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.provider.Settings.EXTRA_APP_PACKAGE
import android.provider.Settings.EXTRA_CHANNEL_ID
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.example.usbhidtool.HidPageActivity
import com.example.usbhidtool.R


/**
 * 上门回收通知栏管理类
 *
 * 为了兼容个版本通知：
 * 使用：NotificationCompat和 NotificationManagerCompat进行通知的创建
 *
 * 创建步骤：
 * 1、创建渠道：在android8.0以上需要创建，以下不用创建
 * 2、设置点击事件
 * 3、构造Notification对象并显示通知
 */
object MyNotiManager {

    private val TAG = "NotificationManager"
    private val CHANNEL_ID = "SuperCallService_channel_1"
    private val CHANNEL_NAME_FOR = "上门超人前台通知"
    private val CHANNEL_NAME_NORMAL = "上门超人普通通知"


    /**
     * ===8.0及以上===
     *现在必须将单个通知放入特定渠道中。
     *用户现在可以按渠道关闭通知，而不是关闭应用的所有通知。
     *包含活动通知的应用会在应用图标上方显示通知“标志”。（小圆点或数字）
     *用户可以暂停抽屉式通知栏中的通知。您可以为通知设置自动超时。
     *可以设置通知的背景颜色。
     */

    /**
     * 创建Channel
     */
    private fun createNotificationChannel(
            context: Context,
            channelID: String,
            channelNAME: String,
            level: Int
    ): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager: NotificationManager =
                    context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel = NotificationChannel(channelID, channelNAME, level);
            manager.createNotificationChannel(channel);
            channelID
        } else {
            CHANNEL_ID
        }
    }


    /**
     * 在前台服务中，创建前台的通知栏，用户无法关闭通知栏
     */
    @TargetApi(26)
    fun setForegroundNotification(context: Service) {
        val manager: NotificationManager =
                context.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
        val channel =
                NotificationChannel(CHANNEL_ID, CHANNEL_NAME_FOR, NotificationManager.IMPORTANCE_HIGH)
        channel.enableLights(true)//设置提示灯
        channel.lightColor = Color.RED//设置提示灯颜色
        channel.setShowBadge(true)//显示logo
        channel.description = "bottombar notification";//设置描述
        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC; //设置锁屏可见 VISIBILITY_PUBLIC=可见
        manager.createNotificationChannel(channel)
        val notification: Notification = Notification.Builder(
                context,
                CHANNEL_ID
        )
                .setAutoCancel(false)
                .setContentTitle("上门超人")
                .setContentText("上门超人服务运行中")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
                .build()
        context.startForeground(1, notification)
    }

    /**
     * 显示通知
     */
    fun showNotifyCation(context: Context, messageId: Int, title: String, content: String) {
        val intent = Intent(context, HidPageActivity::class.java)
        intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
        val channelId = createNotificationChannel(
                context,
                CHANNEL_ID,
                CHANNEL_NAME_NORMAL,
                NotificationManager.IMPORTANCE_HIGH
        )
        val notification = NotificationCompat.Builder(context, channelId)
                .setContentTitle(title)
                .setContentText(content)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true) //点击消失
        val notificationManager = NotificationManagerCompat.from(context)
        notificationManager.notify(messageId, notification.build())
    }

    fun showNotifyCation(context: Context, clientMessage: ClientMessage) {
        showNotifyCation(
                context,
                clientMessage.msgId ?: 100,
                clientMessage.title,
                clientMessage.message
        )
    }

    /**
     * 检测通知权限是否默认打开
     */
    fun isNotifycationOpened(context: Context) {
        if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) {
            Toast.makeText(context, "通知栏权限被禁用", Toast.LENGTH_LONG).show()
            try {
                //根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
                val intent = Intent()
                intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                intent.putExtra(EXTRA_APP_PACKAGE, context.packageName)
                intent.putExtra(EXTRA_CHANNEL_ID, context.applicationInfo.uid)
                //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
                intent.putExtra("app_package", context.packageName)
                intent.putExtra("app_uid", context.applicationInfo.uid)
                context.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                // 出现异常则跳转到应用设置界面：锤子坚果3——OC105 API25
                val intent = Intent()
                //下面这种方案是直接跳转到当前应用的设置界面。
                //https://blog.csdn.net/ysy950803/article/details/71910806
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri: Uri = Uri.fromParts("package", context.getPackageName(), null)
                intent.data = uri
                context.startActivity(intent)
            }
        }

    }
}